import * as types from "./actionTypes";
import { request } from "@apis/request";
import toast from "@utils/showToast";
// import io from 'socket.io-client'

// export const openRegisterAction = bool => ({ type: IS_OPEN_REGISTER, data: bool })
// export const openLoginAction = bool => ({ type: IS_OPEN_LOGIN, data: bool })
// export const openCreateTaskAction = bool => ({ type: IS_OPEN_CREATE_TASK, data: bool })
/**利用函数柯里化创建同步action，将上面的函数转化为如下形式： */
export const createAction = (type) => (data) => ({ type, data });
export const openRegisterAction = createAction(types.IS_OPEN_REGISTER);
export const openLoginAction = createAction(types.IS_OPEN_LOGIN);
export const openCreateTaskAction = createAction(types.IS_OPEN_CREATE_TASK);

/**异步aciton */

export const getLoginProfileAction = () => {
    return async (dispatch) => {
        const res = await request("/users/loginProfile");
        if (res.code === "0000") {
            dispatch(createAction(types.LOGIN_USER_PROFILE)(res.data));
        }
    };
};

export const exitLoginAction = () => {
    return async (dispatch) => {
        const res = request("/api/exitLogin", {}, "post");
        if (res.code === "0000") {
            dispatch(createAction(types.EXIT_LOGIN)(res.data));
        }
    };
};

export const getTaskListAction = (type) => {
    return async (dispatch) => {
        const res = await request("/api/taskLists", { type });
        if (res.code === "0000") {
            dispatch(createAction(types.GET_TASK_LIST)(res.data));
        }
    };
};

export const payAction = (username, payAmount, payChannel) => {
    return async (dispatch) => {
        const res = await request(
            "/api/recharge",
            {
                _username: username,
                money: parseInt(payAmount),
                paymentChannel: payChannel,
            },
            "post"
        );
        dispatch(createAction(types.PAYMENT)(res.data));
        if (res.code === "0000") {
            toast.success("充值成功！");
        } else {
            toast.fail(res.msg);
        }
    };
};

export const getGMoneyAction = () => {
    return async (dispatch) => {
        const res = await request("/api/gmoney");
        dispatch(createAction(types.GET_GMONEY)(res.data));
    };
};

export const rechargeRecordAction = (currentPage, type, numbersOnePage) => {
    return async (dispatch) => {
        const res = await request("/api/rechargeConsume", {
            currentPage,
            type,
            numbersOnePage,
        });
        if (res.code === "0000") {
            dispatch(createAction(types.RECHARGE_RECORD)(res.data));
        } else {
            console.log(res.msg);
        }
    };
};

export const consumeDetailsAction = (currentPage, type, numbersOnePage) => {
    return async (dispatch) => {
        const res = await request("/api/rechargeConsume", {
            currentPage,
            type,
            numbersOnePage,
        });
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.CONSUME_DETAILS)(res.data));
        } else {
            console.log(res.msg);
        }
    };
};

export const onSellGoodsAction = (params, navigate) => {
    return async (dispatch) => {
        const res = await request("/mall/sell", params, "post");
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.ON_SELL_GOODS)(res.data));
            toast.success("上架成功！");
            navigate("/my/goods", { replace: true });
        } else {
            console.log(res.msg);
        }
    };
};

export const getMyGoodsAction = (userName) => {
    return async (dispatch) => {
        const res = await request("/mall/mygoods", { userName: userName });
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.GET_MY_GOODS)(res.data));
        } else {
            console.log(res.msg);
        }
    };
};

export const operationMyGoddsAction = (goodsId, type) => {
    return async (dispatch) => {
        const res = await request(
            "/mall/changeGoodsState",
            { goodsId, type },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.OPERATION_MY_GOODS)(type));
            toast.success("操作成功");
        } else {
            console.log(res.msg);
            toast.fail("操作失败");
        }
    };
};

export const payGmoneyAction = (sellerUserName, goodsId, price, navigate) => {
    return async (dispatch) => {
        const res = await request(
            "/mall/paygmoney",
            { sellerUserName, goodsId, price },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.PAY_GMONEY)(res.data));
            toast.success("操作成功");
            navigate("/m/payDetails", { replace: true });
        } else if (res.code === "0012") {
            toast.fail("登录失效或缺少请求头参数");
        } else if (res.code === "0002") {
            console.log("缺少必要参数");
        } else if (res.code === "0018") {
            toast.fail("不能购买自己的宝贝");
        } else if (res.code === "0014") {
            toast.fail("该商品已下架");
        } else if (res.code === "0015") {
            toast.fail("该商品已售出");
        } else if (res.code === "0016") {
            toast.fail("该商品价格已变更");
        } else if (res.code === "0017") {
            toast.fail("G币余额不足");
        }
    };
};

export const addCartAction = (sellerUserName, goodsId) => {
    return async (dispatch) => {
        const res = await request(
            "/mall/addcart",
            { sellerUserName, goodsId },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.ADD_CART)(res.data));
            toast.success("放入购物车啦");
        } else if (res.code === "0012") {
            toast.fail("登录失效或缺少请求头参数");
        } else if (res.code === "0002") {
            console.log("缺少必要参数");
        } else if (res.code === "0019") {
            toast.fail("不能收藏自己的宝贝");
        } else if (res.code === "0014") {
            toast.fail("该商品已下架");
        } else if (res.code === "0015") {
            toast.fail("该商品已售出");
        } else if (res.code === "0020") {
            toast.fail("不能重复加入");
        }
    };
};

export const getFirstChatDateAction = (goodsId) => {
    return async (dispatch) => {
        const res = await request("/chat/firstJoinChatDate", { goodsId });
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.GET_FIRST_JOIN_CHAT)(res.data));
        } else if (res.code === "0012") {
            toast.fail("请先登录");
        } else if (res.code === "0002") {
            toast.fail("缺少goodId");
        }
    };
};

export const getSingleGoodsIdAction = (goodsId) => {
    return async (dispatch) => {
        const res = await request("/mall/singleGoods", { goodsId });
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.GET_SINGLE_GOODSID)(res.data));
        }
    };
};

// function initIO() {
//   if (!io.socket) {

//     io.socket = io('ws://localhost:4000')

//     io.socket.on('connect', () => {
//       console.log('前端: socket已连接...')
//     })

//     io.socket.on('disconnect', () => {
//       console.log('前端: socket已断开...')
//     })
//   }
// }

// initIO()

export const getContentListAction = (goodsId, from, to) => {
    return async (dispatch) => {
        // initIo(goodsId, from, dispatch)
        // initIO()

        // io.socket.on('receiveMsg', function (msg) {

        //   console.log('前端接收到后端发来的消息：', msg)

        //   if (goodsId === msg.goodsId && (from === msg.from || from === msg.to)) {

        //     dispatch(createAction(types.RECEIVE_MSG)(msg))
        //   }

        // })

        const res = await request("/chat/contentList", { goodsId, from, to });
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.GET_CONTENT_LIST)(res.data));
        } else {
            toast.fail(res.msg);
        }
    };
};

// export const sendMsgAction = (msg) => {
//   return dispatch => {
//     console.log('客户端向服务器发送消息', msg)

//     io.socket.emit('sendMsg', msg)
//   }
// }

// export const adviseAtChatWindowAction = (msg) => {
//   return dispatch => {
//     console.log('消息接收人告知是否在当前聊天窗口：', msg)

//     io.socket.emit('atChatWindow', msg)
//   }
// }

// export const receiveAtChatWindowAction = () => {
//   return dispatch => {

//     initIO()

//     io.socket.on('replyAtChatWindow', function (msg) {
//       console.log('消息接收人是否在当前的聊天窗口：', msg)

//       dispatch(createAction(types.REAL_TIME_READ_MSG)(msg))
//     })

//   }
// }

export const getChatUsersListAction = () => {
    return async (dispatch) => {
        const res = await request("/chat/chatUsersList");
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.GET_CHAT_USERS_LIST)(res.data));
        } else {
            console.log(res.msg);
        }
    };
};

export const changeManyToReadAction = (goodsId, chatUser) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/changeManyToRead",
            { goodsId, chatUser },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            dispatch(createAction(types.CHANGE_MANY_TO_READ)(res.data));
        } else {
            console.log(res.msg);
        }
    };
};
